package app.controller.core
{
	import app.model.flare.proxies.FlareDataProxy;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.command.SimpleCommand;

	public class OpenXMLCmd extends SimpleCommand
	{
		override public function execute(notification:INotification):void{
			var url:String = notification.getType();
			aquire( url )
		}
		
		private function aquire( url:String ):void{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onLoadComplete);
			loader.load(new URLRequest(url));
		}
		
		private function onLoadComplete(event:Event):void{
			var a:Array,
				loader:URLLoader;
			loader = URLLoader( event.target );
			a = decode(new XML(loader.data)) as Array;
			parse( a );
		}
		
		private function decode( xml:XML ):Array{
			var list:XMLList = xml.state,
				a:Array = [],
				o:Object;
			
			for each(var state:XML in list){
				o = {}
				o.fullPath = "root."+stripOutName( state.@name );
				
				if(state.@entering.toString() == ""){
					o.entering = false;
				}else{
					o.entering = true;
				}
				if(state.@exiting.toString() == ""){
					o.exiting = false;
				}else{
					o.exiting = true;
				}
				if(state.@changed.toString() == ""){
					o.changed = false;
				}else{
					o.changed = true;
				}
				
				o.targets =decodeTargets( state.transition );
				a.push(o);
			}	
			
			markInitial(a, "root."+stripOutName( xml.@initial ))
			
			return a;
		}
		
		
		private function markInitial( a:Array, fullPath:String):void{
			for each (var o:Object in a ){
				if(o.fullPath == fullPath){
					o.initial = true;
					return;
				}
			}
		}
		private function decodeTargets( list:XMLList ):Array{
			var a:Array = [],
				o:Object;
			
			for each(var action:XML in list){
				o = {};
				o.name = stripOutName( action.@action );
				o.target = "root."+stripOutName( action.@target );
				a.push(o);
			}	
			
			return a;
		}
		
		private function stripOutName(s:String):String{
			var split:Array = s.split("/");
			return split[split.length-1]
		}
		
		private function parse( a:Array ):void{
			FlareDataProxy(facade.retrieveProxy(FlareDataProxy.NAME)).parse( a );
		}
		
	}
}